package com.omega.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.omega.exam.Exception.BaseException;
import com.omega.exam.entity.*;
import com.omega.exam.mapper.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.omega.exam.service.*;
import com.omega.exam.vo.SubmitAnswerVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 考试服务实现类
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamService {
    @Resource
    private ExamRecordService examRecordService;
    @Resource
    private AnswerRecordMapper answerRecordMapper;
    @Resource
    private PaperService paperService;
    @Resource
    private PaperQuestionMapper paperQuestionMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private QuestionAnswerMapper questionAnswerMapper;
    @Resource
    private KimiAiService kimiAiService;
    @Resource
    private AnswerRecordService answerRecordService;

    @Transactional(rollbackFor = Exception.class)
    public void submit(Integer examRecordId, List<SubmitAnswerVo> answers) throws InterruptedException {
        ExamRecord examRecord = examRecordService.getById(examRecordId);
        if (examRecord == null) {
            throw new BaseException("记录不存在");
        }
        examRecord.setStatus("已完成");
//        examRecord.setAnswers(answers.toString());
        examRecord.setEndTime(LocalDateTime.now());
        examRecordService.updateById(examRecord);
        for (SubmitAnswerVo submitAnswerVo : answers) {
            AnswerRecord answerRecord = new AnswerRecord();
            answerRecord.setExamRecordId(examRecordId);
            answerRecord.setQuestionId(submitAnswerVo.getQuestionId());
            answerRecord.setUserAnswer(submitAnswerVo.getUserAnswer());
            answerRecordMapper.insert(answerRecord);
        }
        gradeExam(examRecordId);
    }

    public ExamRecord gradeExam(Integer examRecordId) throws InterruptedException {
        LambdaQueryWrapper<ExamRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ExamRecord::getStatus, "已完成");
        ExamRecord examRecord = examRecordService.getOne(lambdaQueryWrapper);
        Paper paper = paperService.getById(examRecord.getExamId());
        if (paper == null) {
            examRecord.setStatus("已批阅");
            examRecord.setAnswers("考试对应的试卷被删除！");
            updateById(examRecord);
            throw new RuntimeException("考试对应的试卷被删除,无法进行成绩判定");
        }
        LambdaQueryWrapper<AnswerRecord> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(AnswerRecord::getExamRecordId, examRecordId);
        List<AnswerRecord> list = answerRecordMapper.selectList(lambdaQueryWrapper1);
        System.out.println(list + "list");
        if (ObjectUtils.isEmpty(list)) {
            examRecord.setStatus("已批阅");
            examRecord.setScore(0);
            examRecord.setAnswers("没有提交记录！成绩为0！");
            updateById(examRecord);
            return examRecord;
        }
        //正确题目数量
        //总得分
        int correctNumber = 0;
        int totalScore = 0;
        LambdaQueryWrapper<PaperQuestion> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(PaperQuestion::getPaperId, paper.getId());
        List<PaperQuestion> list1 = paperQuestionMapper.selectList(lambdaQueryWrapper2);
        List<Question> list2 = new ArrayList<>();
        for (PaperQuestion paperQuestion : list1) {
            LambdaQueryWrapper<Question> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper3.eq(Question::getId, paperQuestion.getQuestionId());
     Question question=questionMapper.selectOne(lambdaQueryWrapper3);
       list2.add(question);
        }
        paper.setQuestions(list2);
        for (Question question:paper.getQuestions()){
            LambdaQueryWrapper<QuestionAnswer> lambdaQueryWrapper4=new LambdaQueryWrapper<>();
            lambdaQueryWrapper4.eq(QuestionAnswer::getQuestionId,question.getId());
            QuestionAnswer questionAnswer=questionAnswerMapper.selectOne(lambdaQueryWrapper4);
            question.setAnswer(questionAnswer);
        }
        //正确题目转成map，方便每次判断获取正确答案
        Map<Long,Question> questionMap=paper.getQuestions().stream().collect(Collectors.toMap(Question::getId,q->q));
        for (AnswerRecord answerRecord:list){
            try {
                //先获取，答题记录对应的题目对象
                Question question=questionMap.get(answerRecord.getQuestionId().longValue());
                String systemAnswer=question.getAnswer().getAnswer();
                String userAnswer=answerRecord.getUserAnswer();
                if("JUDGE".equalsIgnoreCase(question.getType())){
                    userAnswer=normalizeJudgeAnswer(userAnswer);
                }
                if(!"TEXT".equals(question.getType())){
                    if(systemAnswer.equalsIgnoreCase(userAnswer)){
                        answerRecord.setIsCorrect(1);
                        answerRecord.setScore(question.getPaperScore().intValue());
                    }else{
                        answerRecord.setScore(0);
                        answerRecord.setIsCorrect(0);
                    }
                }else {
                    //简答题进行AI判断
                    GradingResult result=kimiAiService.gradingTextQuestion(question,userAnswer,question.getPaperScore().intValue());
                    answerRecord.setScore(result.getScore());
                    //ai评价 正确 feedback不正确
                    if(result.getScore() == 0){
                        answerRecord.setIsCorrect(0);
                        answerRecord.setAiCorrection(result.getReason());
                    }else if(result.getScore() == question.getPaperScore().intValue()){
                        answerRecord.setIsCorrect(1);
                        answerRecord.setAiCorrection(result.getFeedback());
                    }else {
                        answerRecord.setIsCorrect(2);
                        answerRecord.setAiCorrection(result.getReason());

                    }

                }
            }catch (Exception e){
                answerRecord.setScore(0);
                answerRecord.setIsCorrect(0);
                answerRecord.setAiCorrection("判断过程出错");
            }
            totalScore+=answerRecord.getScore();
            if(answerRecord.getIsCorrect() == 1){
                correctNumber++;
            }
        }
        answerRecordService.updateBatchById(list);
        //ai评价
        String summary=kimiAiService.buildSummary(totalScore,paper.getTotalScore().intValue(),paper.getQuestionCount(),correctNumber);
        examRecord.setScore(totalScore);
        examRecord.setAnswers(summary);
        examRecord.setStatus("已批阅");
        updateById(examRecord);
        return examRecord;






    }

    private String normalizeJudgeAnswer(String userAnswer) {
        if(userAnswer == null || userAnswer.trim().isEmpty()){
            return "";
        }
        String normalized=userAnswer.trim().toUpperCase();
        switch (normalized){
            case "T":
            case "TRUE":
            case "正确":
                return "TRUE";
            case "F":
            case "FALSE":
            case "错":
                return "FALSE";
            default:
                return normalized;
        }
    }
} 